using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace LogFileViewer
{
    class LogfileSplitter : LogfileAccess
    {
        public LogfileSplitter(FileStream str) : base(str)
        {
        }

        /// <summary>
        ///     Parses a log file and splits it directly into several sub streams (each one for every type).
        /// </summary>
        /// <param name="filenames"></param>
        public void splitLogfile(LogFile[] logFiles)
        {
            this.startProcess("Dividing log file into segments...");

            if (logFiles == null || logFiles.Length < 2)
            {
                Console.WriteLine("File will not be splitted.");
                return;
            }
            this.incrementProgressBar();

            // Open separate output streams for every type
            StreamWriter[] streams = new StreamWriter[5];

            /// Scan file line by line and categorize them
            string tempLine;
            int number = 0;
            StreamWriter lastUsedWriter = null;
            do
            {
                tempLine = streamReader.ReadLine();
                if (tempLine != null)
                {
                    bool isFirstLine = true;
                    int start = tempLine.IndexOf('[');
                    int end = tempLine.IndexOf(']');
                    if (start == -1 || end == -1)
                    {
                        isFirstLine = false;
                    }
                    string type = null;
                    if (isFirstLine)
                    {
                        type = tempLine.Substring(start + 1, end - start - 1);
                        if (type == null)
                        {
                            isFirstLine = false;
                        }
                    }
                    if (isFirstLine && type != null)
                    {
                        for (int i = 0; i < MessageType.Length(); i++)
                        {
                            // Separate entries
                            if (type.Equals(MessageType.StringArray()[i]))
                            {
                                streams[i] = new StreamWriter(logFiles[i].Filename);
                                streams[i].WriteLine(tempLine);
                                lastUsedWriter = streams[i];
                            }
                        }
                    }
                    else
                    {
                        // Check if lastUsedWriter is null which means the first line is corrupt
                        if (lastUsedWriter == null)
                        {
                            // Skip corrupt line
                            continue;
                        }
                        lastUsedWriter.WriteLine(tempLine);
                    }

                    // update progress bar
                    number += tempLine.Length;
                    long filelength = streamReader.BaseStream.Length;
                    int realnumber = number;
                    if ((filelength - Int32.MaxValue) >= 0)
                    {
                        // Number is bigger than integer
                        realnumber = (int)(number / filelength);
                    }

                    this.incrementProgressBar();
                }
            } while (tempLine != null);

            closeStreams();
            for (int i = 0; i < streams.Length; i++)
            {
                streams[i].Flush();
                streams[i].Close();
                streams[i].Dispose();
            }

            deleteEmptyFiles(logFiles);

            this.stopProcess();
        }

        /// <summary>
        ///     Check for empty files and delete them (doesn't work).
        /// </summary>
        private void deleteEmptyFiles(LogFile[] logfiles)
        {
            bool nix = true;
            if (nix)
            {
                try
                {
                    for (int i = 0; i < logfiles.Length; i++)
                    {
                        if (File.Exists(logfiles[i].Filename) && File.OpenRead(logfiles[i].Filename).Length == 0)
                        {
                            File.Delete(logfiles[i].Filename);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

            }
        }
    }
}
